<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="负责人的电话或者姓名等信息" prop="managerId">-->
<!--        <el-input-->
<!--          v-model="queryParams.managerId"-->
<!--          placeholder="请输入负责人的电话或者姓名等信息"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="场所名称" prop="placeName">
        <el-input
          v-model="queryParams.placeName"
          placeholder="请输入场所名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="场所图片" prop="image">-->
<!--        <el-input-->
<!--          v-model="queryParams.image"-->
<!--          placeholder="请输入场所图片"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="场所类型ID" prop="typeId">
        <el-input
          v-model="queryParams.typeId"
          placeholder="请输入场所类型ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="详细地址" prop="address">-->
<!--        <el-input-->
<!--          v-model="queryParams.address"-->
<!--          placeholder="请输入详细地址"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="场所描述" prop="description">-->
<!--        <el-input-->
<!--          v-model="queryParams.description"-->
<!--          placeholder="请输入场所描述"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['place:place:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['place:place:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['place:place:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['place:place:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="placeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="负责人的姓名" align="center" prop="user.nickName" />
      <el-table-column label="负责人的电话" align="center" prop="user.phonenumber" />
      <el-table-column label="场所名称" align="center" prop="placeName" />
      <el-table-column label="场所图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <el-image
            :src="getMinioImageUrl(scope.row.image)"
            fit="scale-down"
            :preview-src-list="[getMinioImageUrl(scope.row.image)]">
          </el-image>
        </template>
<!--        <template slot-scope="scope">-->
<!--          <image-preview :src="scope.row.image" :width="50" :height="50"/>-->
<!--        </template>-->
      </el-table-column>
      <el-table-column label="场所类型" align="center" prop="placeType.typeName" />
      <el-table-column label="详细地址" align="center" prop="address" />
      <el-table-column label="场所描述" align="center" prop="description" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          {{  String(scope.row.status) === 0 ? '关闭' :  '运营中'}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['place:place:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['place:place:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改场所信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="负责人" prop="user.nickName">-->
<!--          <el-input v-model="form.user.nickName" placeholder="请输入负责人姓名" />-->
<!--        </el-form-item>-->
        <el-form-item label="场所名称" prop="placeName">
          <el-input v-model="form.placeName" placeholder="请输入场所名称" />
        </el-form-item>
        <el-form-item label="场所图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/common/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.image" :src="'http://localhost:9000/zfr/' + form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
<!--          <image-upload v-model="form.image" />-->
        </el-form-item>
<!--        <el-form-item label="场所类型ID" prop="placeType.typeName">-->
<!--          <el-input v-model="form.placeType.typeName" placeholder="请输入场所类型" />-->
<!--        </el-form-item>-->
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="场所描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入场所描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPlace, getPlace, delPlace, addPlace, updatePlace } from "@/api/place/place"

export default {
  name: "Place",
  data() {
    return {
      // MinIO 配置
      minioConfig: {
        endpoint: 'http://127.0.0.1:9000/',  // MinIO 服务器地址
        bucketName: 'zfr',           // 存储桶名称
        accessKey: 'adminminio',           // 访问密钥
        // secretKey: 'adminminio'            // 秘密密钥（前端不应暴露，这里仅作示例，实际应通过后端签名）
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 场所信息表格数据
      placeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        managerId: null,
        placeName: null,
        image: null,
        typeId: null,
        address: null,
        description: null,
        status: null,
      },
      // 表单参数
      form: {
        // user:{},
        // placeType:{}
      },
      // 表单校验
      rules: {
        placeName: [
          { required: true, message: "场所名称不能为空", trigger: "blur" }
        ],
        typeName: [
          { required: true, message: "场所类型ID不能为空", trigger: "blur" }
        ],
        address: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    }
  },
  computed: {
    // MinIO 图片访问URL前缀
    minioImagePrefix() {
      return `${this.minioConfig.endpoint}/${this.minioConfig.bucketName}/`;
    },
    // MinIO 上传URL
    minioUploadUrl() {
      // 实际项目中应调用后端接口获取上传URL或签名

      return `${this.minioConfig.endpoint}/${this.minioConfig.bucketName}`;
    },
    // MinIO 上传请求头（如果需要）
    minioHeaders() {
      // 注意：不要在前端暴露secretKey，应通过后端获取临时凭证
      return {};
    }
  },
  created() {

    this.getList()


  },
  methods: {
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.user.length;
      this.checkAll = checkedCount === this.placeType.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.user.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.placeType.length;
      this.form.user = value
      this.form.placeType = value
      console.log(value)
      console.log("-------")
      console.log(this.form.user)
      console.log(this.form.placeType)
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    handleAvatarSuccess(res, file) {
      console.log(res.msg)
      console.log(555)
      this.form.image = res.msg;
    },
    beforeAvatarUpload(file) {
    //   const isJPG = file.type === 'image/jpeg';
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //
    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!');
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!');
    //   }
    //   return isJPG && isLt2M;
    },
    // // 生成MinIO图片URL
    getMinioImageUrl(imageName) {
      const url = `${this.minioConfig.endpoint}${this.minioConfig.bucketName}/${imageName}`;
      // console.log('[图片URL]', imageName, '→', url); // 打印原始文件名和生成的URL
      // console.log(777)
      // console.log(imageName)
      // console.log(url)
      return url;
    },
    // getMinioImageUrl(imageName) {
    //   // if (!imageName) return 'https://picsum.photos/100/100'; // 默认占位图
    //
    //   // 如果是完整URL则直接返回
    //   if (imageName.startsWith('http')) return imageName;
    //
    //   // 拼接MinIO服务器URL
    //   return `${this.minioImagePrefix}${imageName}`;
    // },

    // 自定义上传方法（如果需要）
    customUpload(file) {
      // 这里可以实现自定义上传逻辑，例如获取签名、处理进度等
      // 实际项目中建议通过后端服务处理MinIO上传
      return new Promise((resolve, reject) => {
        // 示例：使用axios上传到MinIO
        // axios.post(this.minioUploadUrl, file, {
        //   headers: this.minioHeaders
        // })
        // .then(response => {
        //   resolve(response.data);
        // })
        // .catch(error => {
        //   reject(error);
        // });

        // 由于安全限制，这里简化处理，实际项目中应通过后端上传
        resolve(file.name);
      });
    },
    /** 查询场所信息列表 */
    getList() {
      this.loading = true
      listPlace(this.queryParams).then(response => {
        console.log("---------")

        console.log(response)
        this.placeList = response.rows
        // for (var i=0;i<response.total;i++){
        //   this.placeList[i].placeType=response.rows[i].placeType
        // }
        // this.placeList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        managerId: null,
        placeName: null,
        image: null,
        typeId: null,
        address: null,
        description: null,
        status: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加场所信息"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPlace(id).then(response => {
        console.log(response)
        this.form = response.data
        console.log(this.form)
        this.open = true
        this.title = "修改场所信息"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePlace(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPlace(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除场所信息编号为"' + ids + '"的数据项？').then(function() {
        return delPlace(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('place/place/export', {
        ...this.queryParams
      }, `place_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
